﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

using WeChatDemo.DataProvider.Photo;
using WeChatDemo.Models.Photo;
using WeChatDemo.Models.DTO.Photo;

namespace WeChatDemo.Controllers
{
    public class PhotoUserController : ApiController
    {
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        [HttpPost]
        public IHttpActionResult Post([FromBody]PhotoUser model)
        {
            //测试OpenID:oRMP5shI6hdqW7Fs7quu9yuU3HKg
            model.ID = Guid.NewGuid();
            //model.WechatOpenId = "oRMP5shI6hdqW7Fs7quu9yuU3HKg";

            if (DAOPhotoUser.Add(model))
            {
                return Created<PhotoUser>("success", model);
            }
            else
            {
                return InternalServerError();
            }
        }

        [HttpGet]
        public IHttpActionResult Get(string id)
        {
            return Ok(new { result = DAOPhotoUserDetails.GetModel(new Guid(id)) });
        }

        [HttpGet]
        public IHttpActionResult Get(string userName, string mobile)
        {
            return Ok(new { result = DAOPhotoUserDetails.GetModel(userName, mobile) });
        }

        [HttpGet]
        [Route("api/photouser/checkopenid")]
        public IHttpActionResult GetByOpenId([FromUri]string openid)
        {
            try
            {
                IEnumerable<DTOPhotoUser> _list = null;
                _list = DAOPhotoUserDetails.GetList($"AND WechatOpenId = '{openid}'");
                
                if (_list.Count<DTOPhotoUser>() == 0)
                {
                    return Ok(new { count = 0 });
                }
                else
                {
                    return Ok(new { count = 1, result = _list.SingleOrDefault<DTOPhotoUser>() });
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet]
        [Route("api/photouser/checkmobile")]
        public IHttpActionResult IsMobileAvailble([FromUri]string mobile)
        {
            return Ok(new { result = DAOPhotoUserDetails.GetModel(mobile) });
        }

        [HttpPut]
        public IHttpActionResult Put([FromBody]PhotoUser model)
        {
            if (DAOPhotoUser.Update(model))
            {
                return Ok<PhotoUser>(model);
            }
            else
            {
                return InternalServerError();
            }
        }
    }
}